#include "visualrecognition.h"
#include <QFile>
#include "../../HttpServer/httpsend.h"
#include "component_log.h"
#include "json_trans.h"

#define API ("/api/recognization")

VisualRecognition::VisualRecognition()
{}

VisualRecognition::~VisualRecognition()
{}

bool VisualRecognition::Init(const VisRecogParam param)
{
	m_path = param.path;
	if (m_path.isEmpty()) {
		log_error("path is empty");
		return false;
	}

	log_trace("visual recognization path is {}", m_path);
	return false;
}

int VisualRecognition::GetRecognitionResult(const QString& rgb, RecResult& result)
{
	QByteArray ans;
	if (PostRGBFile(rgb, ans)) {
		result.fromJson(ans);
		return result.rects().size();
	}
	log_error("post failed");
	return -1;
}


bool VisualRecognition::PostRGBFile(const QString& file, QByteArray& result)
{
	QByteArray ans;
	QByteArray data;
	QFile f(file);
	if (f.open(QIODevice::ReadOnly)) {
		data = f.readAll().toBase64();
		f.close();
	} else {
		log_error("rgb file[{}] open failed", file);
		return false;
	}

	QString path = m_path + API;
	int ret = HttpSend::SendPostMsgByHttp(path, data, ans, false);
	if (ret == send_ok) {
		result = ans;
		return true;
	} else {
		log_error("send visual recognize data failed, ret = {}, ans = {}", ret, ans);
		return false;
	}
}

json_struct(StatusInfo,
	mapping(QString, status);
prop(&status);
);

bool VisualRecognition::TestForServe()
{
	QByteArray ans;
	QString path = m_path + API;
	int ret = HttpSend::SendGetMsgByHttp(path, ans);
	if (ret != send_ok) {
		log_error("Get TestInfo  error");
		return false;
	}
	StatusInfo info = {};
	info.fromJson(ans);
	if (info.status() != "available") {
		log_error("Get test info error, ans = {}", ans);
		return false;
	}
	return true;
}
